import { execSync } from 'child_process';
import fs from 'fs';
import path from 'path';

async function extractJavaScript(fileName) {
  try {
    const currentDir = process.cwd();
    const filePath = path.resolve(currentDir, fileName);
    console.log('处理文件路径:', filePath);

    // 检查文件是否存在
    if (!fs.existsSync(filePath)) {
      throw new Error('文件不存在');
    }

    // 创建输出目录
    const outputDir = path.resolve('temp', 'solana-mev-bot-1.0.14');
    if (!fs.existsSync(outputDir)) {
      fs.mkdirSync(outputDir, { recursive: true });
    }

    // 使用 strings 命令提取文本
    console.log('开始提取文本...', filePath, fileName);
    const output = execSync(`strings "${filePath}"`, {
      maxBuffer: 1024 * 1024 * 100,
    }).toString();

    // 保存提取的内容
    const baseName = path.basename(fileName);
    const outputFile = path.resolve(outputDir, baseName + '.js');
    fs.writeFileSync(outputFile, output);

    return {
      success: true,
      outputFile,
      content: output,
    };
  } catch (error) {
    return {
      success: false,
      error: error instanceof Error ? error.message : String(error),
    };
  }
}

// 使用示例
async function main() {
  try {
    const result = await extractJavaScript('./temp/solana-mev-bot-1.0.14/download');
    if (result.success) {
      console.log('提取成功！');
      console.log('输出文件:', result.outputFile);
      console.log('提取的代码行数:', result?.content?.split('\n').length);
    } else {
      console.error('提取失败:', result.error);
    }
  } catch (error) {
    console.error('执行错误:', error);
  }
}

main();
